package com.controller;

import java.util.List;
import java.util.Map;
import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.pojo.Archive;
import com.service.ArchiveService;
import com.service.LogService;
import com.service.UserService;

@Controller
public class ArchiveController {
	/* 加载service */
	UserService service = new UserService();
	ArchiveService service1 = new ArchiveService();
	LogService service2 = new LogService();

	/* 添加档案信息 */
	@RequestMapping(value = "/addDA.action", method = RequestMethod.POST)
	@ResponseBody
	public String addDA(
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			@CookieValue(value = "ID", defaultValue = "") String userId,
			HttpServletResponse response) {
		service1.addDA(archive_id, identity, name, gender, birthday,
				date_retire1, date_retire2, sp, fc, title, seniority);
		/* 将添加操作记录到user_log表中 */
		Map<String, Object> map = service1.lastId();
		// System.out.println(map.get("id").toString());
		service2.insert(userId, "添加", map.get("id").toString());
		return "OK"; /* html作判断 */
	}

	/* 右上角小输入框查询获取arvhive表的id */
	@RequestMapping(value = "/chaxun.action", method = RequestMethod.POST)
	@ResponseBody
	public String chaxun(
			@RequestParam(value = "shuru", defaultValue = "") String shuru,
			@CookieValue(value = "ID", defaultValue = "") String userId,
			HttpServletResponse response) {
		List<Archive> list = service1.chaxun(shuru);
		// System.out.println(list);
		/* 通过list的长度判断查到几个人 */
		if (1 < list.size()) {
			return "dayuone";
		} else if (0 == list.size()) {
			return "dengyuO";
		}
		/* 将添加操作记录到user_log表中 */
		service2.insert(userId, "查询", list.get(0).getId());
		// System.out.println(userId);
		// System.out.println(list.get(0).getId());
		/* 返回 查到的档案号的id */
		return list.get(0).getId();
	}

	/* 通过查到的id，把档案的详细信息查到 */
	@RequestMapping(value = "/one.action", method = RequestMethod.GET)
	@ResponseBody
	public Archive one(
			@RequestParam(value = "id", defaultValue = "") String id,
			@CookieValue(value = "ID", defaultValue = "") String userId,
			HttpServletResponse response) {
		Archive list = service1.one(id);
		// System.out.println(list);
		return list;
	}

	/* 修改查到的信息 */
	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			@CookieValue(value = "ID", defaultValue = "") String userId,
			HttpServletResponse response) {
		// System.out.println(id);
		service1.update(id, archive_id, identity, name, gender, birthday,
				date_retire1, date_retire2, sp, fc, title, seniority);
		/* 将添加操作记录到user_log表中 */
		service2.insert(userId, "修改", id);
		return "OK";
	}

	/* 上传文件 */
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@PathVariable String id,
			@RequestParam("file") MultipartFile file,
			@CookieValue(value = "ID", defaultValue = "") String userId,
			HttpServletRequest req) {
		// HttpServletRequest HttpServletResponse
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR";
		}
		try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			Archive archive = service1.one(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload",
					archive.getArchive_id(), newFileName);
			// System.out.println(filePath);
			File existsFile = new File(filePath);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
					System.out.println("删除原始文件：" + filePath);
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			Map<String, Object> map = service1.lastId();
			service1.file(id, newFileName);
			service2.insert(userId, "上传图片", id);
			// System.out.println(archive.getArchive_id());
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERRORasdad";
		}
	}
}
